﻿using System;
using System.Collections.Generic;
using FlanProjectData.Managers;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using FlanProjectData.Characters;
using FlanProjectData.GameObjects;
using FlanProjectData.Helpers;

namespace FlanProject.ScreenMenu
{
    public class InventoryScreen : InterfaceScreen
    {
        #region Properties

        #region Debug

        private static Logger logger = new Logger("InventoryScreen", Log_Type.DEBUG);

        #endregion

        #region Inventory Data

        public Party Team { get; set; }
        private Player currentPlayer = null;
        private int indexPlayer = 0;
        private int indexItemSelect = 1;
        private int oldIndexItemSelect = 1;

        private float widthPercentName = (float)0.50;
        private float heightPercentName = (float)0.15;

        private float distanceBetween2Character = (float)50; // Taille en px entre deux noms (bg)

        private float widthtPercentPositionImageChar = (float)0.45;
        private float heightPercentPositionImageChar = (float)0.15;

        private float distanceBetween2ImageChar = (float)50;

        private float widthPercentImageChar = (float)0.2; // le carré noir derriere le nom du perso
        private float heightPercentImageChar = (float)0.1;

        private float widthtPercentImageLeft = (float)1.6; //le grand carrée noir
        private float heightPercentImageLeft = (float)1.25;

        private float widthtPercentPositionImageLeft = (float)0.02; // BG de l'inventaire
        private float heightPercentPositionImageLeft = (float)0.20;

        private float widthtPercentPositionImageInventory = (float)0.53; // l'image de l'inventaire
        private float heightPercentPositionImageInventory = (float)0.28;

        private float PercentImageInventory = (float)0.9;


        private float PercentImageInv = (float)0.9; // le tableau
        private float distanceBetween2ImageInvC = (float)1.05;
        private float distanceBetween2ImageInvL = (float)1.05;
        private float widthtPercentPositionImageInv = (float)0.07;
        private float heightPercentPositionImageInv = (float)0.74;


        private String message = ""; // les states
        private float widthtPercentPositionStat = (float)0.07;
        private float heightPercentPositionStat = (float)0.20;

        private float policeSize = 1;

        private int debutInventaire =0; // une variable pas belle

        private int indexAffichageStat;
        private int indexInventory;


        MenuEntry imageInventaire;

        private int indexEquipementDebut = 0;
        private int indexEquipementFin = 0;
        private int indexInventaireDebut = 0;
        private int indexInventaireFin = 0;

        private bool doUpdate = false;
        private bool updateEquipement = false;
        private bool updateInventaire = false;

        private ContentManager cmDeTest = null;

        private int indexCol = 1;
        private int pageInventaire = 0;

        private List<MenuEntry> listeEquipement;
        private List<MenuEntry> listeInventaire;
        #endregion

        #endregion

        #region Ctor

        public InventoryScreen(ref Party newTeam)
        {
            logger.Debug("New Inventory screen is intanciate");
            this.lstMenuEntryUnselectable.Add(new MenuEntry(
                "Inventory", new Vector2(0, 0), true, Color.White, policeSize));

            listeInventaire = new List<MenuEntry>();
            listeEquipement = new List<MenuEntry>();

            this.Team = newTeam;
            currentPlayer = this.Team.PlayerList[this.indexPlayer];
            

            //le fond noir de l'inventaire
            this.lstMenuEntryUnselectable.Add(new MenuEntry(true,
               new Vector2((float)windowsWidth * widthtPercentPositionImageLeft,
                       (float)windowsHeight * heightPercentPositionImageLeft),
               @"Sprites\Menus\blackBG",
               new Vector2(widthtPercentImageLeft, heightPercentImageLeft), null, false));

            //l'image de l'inventaire : Personnage
            this.indexInventory = this.lstMenuEntryUnselectable.Count;


           this.imageInventaire = new MenuEntry(true,
               new Vector2((float)windowsWidth * widthtPercentPositionImageInventory,
                       (float)windowsHeight * heightPercentPositionImageInventory),
               @"Sprites\Menus\inv_perso",
               null, PercentImageInventory, true);

           this.lstMenuEntryUnselectable.Add(imageInventaire);

            debutInventaire = this.lstMenuEntryUnselectable.Count;

            //creation du tableau d'image
            for (int l = 0; l < 2; l++)
            {
                for (int c = 0; c < 4; c++)
                {
                    MenuEntry test= new MenuEntry(true,
                        new Vector2((float)windowsWidth * widthtPercentPositionImageInv + (distanceBetween2ImageInvL + 84) * c,
                        (float)windowsHeight * heightPercentPositionImageInv + (distanceBetween2ImageInvC + 73) * l),
                         @"Sprites\Menus\inv_case",
                            null, PercentImageInv, true);
                    test.Select = false;
                    this.lstMenuEntryUnselectable.Add(test);

                }
            }

            

            indexAffichageStat = this.lstMenuEntryUnselectable.Count;
            this.message = creationAffichageStat();
            this.lstMenuEntryUnselectable.Add(new MenuEntry(
                this.message, new Vector2((float)windowsWidth * widthtPercentPositionStat,
                    (float)windowsHeight * heightPercentPositionStat),
                    true, Color.White, (float)0.5));
            

            creationInventairePerso(indexCol);
            creationEquipement();
        }

        #endregion
        public void creationInventairePerso(int idLigne)
        {
            this.indexInventaireDebut = this.lstMenuEntryUnselectable.Count;
            logger.Debug("index debut inventaire: " + indexInventaireDebut);
            for (int i = (idLigne - 1) * 4; i < idLigne * 4; i++)
            {
                for (int l = 0; l < 2; l++)
                {
                    for (int c = 0; c < 4 && i < this.Team.inventory.lstItems.Count; c++)
                    {
                        MenuEntry test = new MenuEntry(true,
                            new Vector2((float)windowsWidth * widthtPercentPositionImageInv + (distanceBetween2ImageInvL + 84) * c,
                            (float)windowsHeight * heightPercentPositionImageInv + (distanceBetween2ImageInvC + 73) * l),
                             this.Team.inventory.lstItems[i].Link,
                                null, PercentImageInv, true);
                        test.Select = false;
                        listeInventaire.Add(test);
                        this.lstMenuEntryUnselectable.Add(test);
                        i++;

                    }
                }
            }
            this.indexInventaireFin = this.lstMenuEntryUnselectable.Count;
            logger.Debug("index fin inventaire: " + indexInventaireFin);
        }

       

        
        public void creationEquipement()
        {

            indexEquipementDebut = this.lstMenuEntryUnselectable.Count;
            logger.Debug("index debut equipement: " + indexEquipementDebut);
            if (this.currentPlayer.Equipement.arms != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(655, 268),
                                this.currentPlayer.Equipement.arms.Link,
                                   null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
            }
                
            if (this.currentPlayer.Equipement.chest != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(655, 170),
                                this.currentPlayer.Equipement.chest.Link,
                                   null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                               
            }
            if (this.currentPlayer.Equipement.foot != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(615, 480),
                                 this.currentPlayer.Equipement.foot.Link,
                                    null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                                
            }
            if (this.currentPlayer.Equipement.head != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(418, 168),
                                  this.currentPlayer.Equipement.head.Link,
                                     null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                                 
            }
            if (this.currentPlayer.Equipement.leftHand != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(655, 370),
                                 this.currentPlayer.Equipement.leftHand.Link,
                                    null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                                
            }
            if (this.currentPlayer.Equipement.rightHand != null)
            {
                MenuEntry Test = new MenuEntry(true,
                               new Vector2(418, 265),
                               this.currentPlayer.Equipement.rightHand.Link,
                                  null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                              
                 
              
            }
            if (this.currentPlayer.Equipement.legs != null)
            {
                MenuEntry Test = new MenuEntry(true,
                                new Vector2(418, 368),
                                this.currentPlayer.Equipement.legs.Link,
                                   null, PercentImageInv, true);
                listeEquipement.Add(Test);
                this.lstMenuEntryUnselectable.Add(Test);
                              
            }
           
            indexEquipementFin = this.lstMenuEntryUnselectable.Count;
            logger.Debug("index fin inventaire: " + indexEquipementFin);
        }

        #region overrided methods

        public override void Draw(SpriteBatch sb)
        {
            base.Draw(sb);
            affichageInventaire(sb);

        }

        public void affichageInventaire(SpriteBatch sb)
        {
            
        }

        public override void HandleInput()
        {
            if (InputManager.IsActionTriggered(InputManager.Action.Up))
            {
                doUpdate = true;

                oldIndexItemSelect = indexItemSelect;
                if (indexItemSelect - 4 < 1)
                {
                    indexItemSelect += +4;
                }
                else
                {
                    indexItemSelect += -4;
                }
                if (indexCol - 1 < 1)
                {

                }
                else
                {
                    indexCol += -1;
                    pageInventaire--;
                    this.updateInventaire = true;
                }
                logger.Debug("index col: " + indexCol);
                
                
            }
            if (InputManager.IsActionTriggered(InputManager.Action.Down))
            {
                doUpdate = true;

                oldIndexItemSelect = indexItemSelect;
                if (indexItemSelect + 4 > 8)
                {
                    indexItemSelect += -4;

                    if (indexCol + 1 > Math.Ceiling((float)this.Team.inventory.lstItems.Count / 4))
                    {

                    }
                    else
                    {
                        indexCol += 1;
                        pageInventaire++;
                        this.updateInventaire = true;
                    }
                }
                else
                {
                    indexItemSelect += +4;
                }
                logger.Debug("index col: " + indexCol);
                
            }
            if (InputManager.IsActionTriggered(InputManager.Action.Left))
            {


                oldIndexItemSelect = indexItemSelect;
                if (indexItemSelect - 1 < 1)
                {
                    indexItemSelect = 8;
                }
                else
                {
                    indexItemSelect += -1;
                }
            }
             if (InputManager.IsActionTriggered(InputManager.Action.Right))
            {
                oldIndexItemSelect = indexItemSelect;
                if (indexItemSelect + 1 > 8)
                {
                    indexItemSelect = 1;
                }
                else
                {
                    indexItemSelect += +1;
                }
            }

            if(InputManager.IsActionTriggered(InputManager.Action.Ok))
            {
                doUpdate = true;
                this.updateEquipement = true;
                this.updateInventaire=true;
                logger.Debug("indexCol: " + (this.pageInventaire));
                logger.Debug("item selection: " + ((8 * (this.pageInventaire)) + (this.indexItemSelect - 1)));

               // Console.WriteLine("case selectioné: "+((8 * (this.pageInventaire)) + (this.indexItemSelect - 1)));
               // Console.WriteLine("taille inventaire: "+this.Team.inventory.lstItems.Count);
              
                if (((8 * (this.pageInventaire)) + (this.indexItemSelect - 1)) < this.Team.inventory.lstItems.Count)
                {
                    //Console.WriteLine("on passe dans le if");
                   // logger.Debug("on change d'equipement: " + this.Team.inventory.lstItems[(8 * (this.pageInventaire)) + (this.indexItemSelect - 1)].Name);
                    this.Team.addItemToCharacter((8 * (this.pageInventaire)) + (this.indexItemSelect - 1), this.indexPlayer);
                }
               
                    
                
                
                
            }

            if (InputManager.IsKeyTriggered(Keys.NumPad4))
            {
                doUpdate = true;
                this.updateEquipement = true;
                selectedIndex = (selectedIndex - 1 + lstMenuEntrySelectable.Count) % lstMenuEntrySelectable.Count;
                logger.Debug(selectedIndex.ToString());

                if (this.indexPlayer - 1 <0)
                    this.indexPlayer = this.Team.PlayerList.Count-1;
                else
                    this.indexPlayer += -1;
            }
            else if (InputManager.IsKeyTriggered(Keys.NumPad6))
            {

                doUpdate = true;
                this.updateEquipement = true;

                selectedIndex = Math.Abs(selectedIndex + 1) % lstMenuEntrySelectable.Count;
                logger.Debug(selectedIndex.ToString());

                if (this.indexPlayer + 1 > this.Team.PlayerList.Count - 1)
                {
                    this.indexPlayer = 0;
                }

                else
                {
                    this.indexPlayer += 1;
                }
                  
                
            }

            if (InputManager.IsActionTriggered(InputManager.Action.Exit))
            {
                this.ExitScreen();
            }
            //logger.Debug("player select: " + this.indexPlayer);
            //this.indexPlayer = selectedIndex;


            /// a enlever
            if (InputManager.IsKeyTriggered(Keys.E))
            {
                affichageTest();
            }
            if (InputManager.IsKeyTriggered(Keys.Z))
            {
                if (this.lstMenuEntryUnselectable[this.debutInventaire-1].Select==true)
                {
                    this.lstMenuEntryUnselectable[this.debutInventaire-1].Select = false;
                }
                else
                {
                    this.lstMenuEntryUnselectable[this.debutInventaire].Select=true;
                }
                
            }
            /// fin enlever
        }

        // au futur lecteur: OUI, c'est TRES moche!!!! (maxime)
        public override void LoadContent(ContentManager cm)
        {
            

            if (doUpdate)
            {
                base.LoadContent(cm);
            }
            else
            {

                this.cmDeTest = cm;
                //TODO Change the background
                this.background = cm.Load<Texture2D>(@"Sprites\Menus\commonBackgroundMenu");

                // calculate the scale of the background
                base.calcScaleBackground(windowsHeight, windowsWidth);

                base.LoadContent(cm);

                // <-- Cette partie est moche mais c'est normal


                int i = 0;
                for (i = 1; i <= this.Team.PlayerList.Count; i++)
                {
                    //bool isImage, Vector2 position, String url, Vector2 newSize, float scale, bool proportionConserv

                    this.lstMenuEntryUnselectable.Add(new MenuEntry(true,
                        //new Vector2((float)windowsWidth * widthtPercentPositionImageChar * (distanceBetween2ImageChar * i),
                   new Vector2(distanceBetween2ImageChar,
                           (float)windowsHeight * heightPercentPositionImageChar),
                   @"Sprites\Menus\blackBG",
                   new Vector2((float)(cm.Load<SpriteFont>("Sprites\\Fonts\\menufont").MeasureString(this.Team.PlayerList[i - 1].Name).X + 10) / 481, (float)(cm.Load<SpriteFont>("Sprites\\Fonts\\menufont").MeasureString(this.Team.PlayerList[i - 1].Name).Y + 20) / windowsHeight), null, false));

                    this.lstMenuEntrySelectable.Add(new MenuEntry(this.Team.PlayerList[i - 1].Name,
                   new Vector2(distanceBetween2ImageChar + 5,
                       (float)windowsHeight * heightPercentName),
                       true, Color.Yellow, policeSize));

                    distanceBetween2ImageChar += cm.Load<SpriteFont>("Sprites\\Fonts\\menufont").MeasureString(this.Team.PlayerList[i - 1].Name).X + 30;
                }
                base.LoadContent(cm);
            }

            

            // --> Fin de la partie moche 
        }


        public void effacerAncienEquipement(int debut, int fin)
        {
            for (int i = debut-1; i < fin-1; i++)
            {
                logger.Debug("on efface l'item numero " + i);
                this.lstMenuEntryUnselectable.RemoveAt(debut);
            }
        }

        public void effacerInventaire()
        {

            if (this.listeInventaire!=null)
            {
                  for (int i = 0; i < this.listeInventaire.Count; i++)
                     {
                            this.lstMenuEntryUnselectable.Remove(this.listeInventaire[i]);
                    }
                this.listeInventaire = new List<MenuEntry>();
            }
          
        }

        public void effacerEquipement()
        {
            if (this.listeEquipement != null)
            {
                for (int i = 0; i < this.listeEquipement.Count; i++)
                {
                    this.lstMenuEntryUnselectable.Remove(this.listeEquipement[i]);
                }
                this.listeEquipement = new List<MenuEntry>();
            }
           
        }

        public override void Update()
        {
            if (doUpdate)
            {

                if (this.updateInventaire)
                {
                    //effacerAncienEquipement(this.indexInventaireDebut, this.indexInventaireFin);
                    
                    effacerInventaire();
                    this.indexInventaireDebut = 0;
                    this.indexInventaireFin = 0;
                    creationInventairePerso(indexCol);
                    this.updateInventaire = false;
                }

                if (this.updateEquipement)
                {
                    this.currentPlayer = this.Team.PlayerList[this.indexPlayer];
                    this.lstMenuEntryUnselectable[indexAffichageStat].message = creationAffichageStat();
                    effacerEquipement();
                    //effacerAncienEquipement(this.indexEquipementDebut, this.indexEquipementFin);
                    this.indexEquipementDebut = 0;
                    this.indexEquipementFin = 0;
                    creationEquipement();
                    this.updateEquipement = false;
                }
               

               
                LoadContent(cmDeTest);
                doUpdate = false;
            }
           
           /* Console.WriteLine(this.debutInventaire +" - "+ this.oldIndexItemSelect + " - "+ this.indexItemSelect);
            for (int i = 0; i < this.lstMenuEntryUnselectable.Count; i++)
            {
                Console.WriteLine("["+i+"] - "+this.lstMenuEntryUnselectable[i].Select);
            }*/
            //logger.Debug(this.currentPlayer.Name);
            this.lstMenuEntryUnselectable[this.debutInventaire - 1 + this.oldIndexItemSelect].Select = false;
            this.lstMenuEntryUnselectable[this.debutInventaire - 1 + this.indexItemSelect].Select = true;

            
            //logger.Debug(this.lstMenuEntryUnselectable[indexAffichageStat - 1].message);
            base.Update();
            
        }

        #endregion

        private string creationAffichageStat()
        {
            string messageCree = this.currentPlayer.Name + " :\n";
            messageCree = messageCree + "Health Points : " + this.currentPlayer.BaseStats.CurrentHealthPoints + "\n";
            messageCree = messageCree + "Strength : " + this.currentPlayer.BaseStats.Strength + "\n";
            messageCree = messageCree + "Resistance : " + this.currentPlayer.BaseStats.Resistance + "\n";
            messageCree = messageCree + "Intelligence : " + this.currentPlayer.BaseStats.Intelligence + "\n";
            messageCree = messageCree + "Accuracy : " + this.currentPlayer.BaseStats.Accuracy + "\n";
            messageCree = messageCree + "Attack Speed : " + this.currentPlayer.BaseStats.AttackSpeed + "\n";
            messageCree = messageCree + "Movement Speed : " + this.currentPlayer.BaseStats.MovementSpeed + "\n";
            messageCree = messageCree + "Defend Percentage : " + this.currentPlayer.BaseStats.DefendPercentage + "\n";
            

            return messageCree;
        }
        private void affichageTest()
        {
            logger.Debug("inventaire: ");
            for (int i = 0; i < this.Team.inventory.lstItems.Count; i++)
            {
                logger.Debug("i: " + i + " " + this.Team.inventory.lstItems[i].Name + "-" + this.Team.inventory.lstItems[i].Type);
            }

            logger.Debug("equipement: ");
            if (this.Team.PlayerList[0].Equipement.arms!=null)
                logger.Debug("arms: "+this.Team.PlayerList[0].Equipement.arms.Name);
            if (this.Team.PlayerList[0].Equipement.chest != null)
                logger.Debug("chest: " + this.Team.PlayerList[0].Equipement.chest.Name);
            if (this.Team.PlayerList[0].Equipement.foot != null)
             logger.Debug("foot: " + this.Team.PlayerList[0].Equipement.foot.Name);
            if (this.Team.PlayerList[0].Equipement.head != null)
                logger.Debug("head: " + this.Team.PlayerList[0].Equipement.head.Name);
            if (this.Team.PlayerList[0].Equipement.leftHand != null)
                logger.Debug("leftHand: " + this.Team.PlayerList[0].Equipement.leftHand.Name);
            if (this.Team.PlayerList[0].Equipement.rightHand != null)
                logger.Debug("rightHand: " + this.Team.PlayerList[0].Equipement.rightHand.Name);
            if (this.Team.PlayerList[0].Equipement.legs != null)
                logger.Debug("legs: " + this.Team.PlayerList[0].Equipement.legs.Name);
        }
    }
}
